package com.sowell.mvpbase.mvputils

import android.R
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.text.*
import android.text.style.*
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import com.ctetin.expandabletextviewlibrary.span.RadiusBackgroundSpan
import com.ctetin.expandabletextviewlibrary.span.SelfImageSpan
import com.lamfire.utils.StringUtils
import com.maoti.lib.BaseManager
import com.maoti.lib.utils.LogUtil

class ViewUtil {
    companion object {
        fun getViewWidth(v: View): Int {
            val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            v.measure(w, h)
            return v.measuredWidth
        }


        fun getViewHeight(v: View): Int {
            val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            v.measure(w, h)
            return v.measuredHeight
        }

        fun matchAll(context: Context, imageView: ImageView, pwidth: Int, pheight: Int) {
            val width: Int
            val height: Int //ImageView调整后的宽高
            //获取屏幕宽高
            val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val metrics = DisplayMetrics()
            manager.defaultDisplay.getMetrics(metrics)
            val sWidth = metrics.widthPixels
            val sHeight = metrics.heightPixels

            //获取图片宽高
            val drawable = imageView.drawable
            val dWidth = drawable.intrinsicWidth
            val dHeight = drawable.intrinsicHeight

            //屏幕宽高比,一定要先把其中一个转为float
            val sScale = sWidth.toFloat() / sHeight
            //图片宽高比
            val dScale = dWidth.toFloat() / dHeight
            /*
            缩放比
            如果sScale>dScale，表示在高相等的情况下，控屏幕比较宽，这时候要适应高度，缩放比就是两则的高之比，图片宽度用缩放比计算
            如果sScale<dScale，表示在高相等的情况下，图片比较宽，这时候要适应宽度，缩放比就是两则的宽之比，图片高度用缩放比计算
             */
            var scale = 1.0f
            if (sScale > dScale) {
                scale = dHeight.toFloat() / sHeight
                height = sHeight //图片高度就是屏幕高度
                width = (dWidth * scale).toInt() //按照缩放比算出图片缩放后的宽度
            } else if (sScale < dScale) {
                scale = dWidth.toFloat() / sWidth
                width = sWidth
                height = (dHeight / scale).toInt() //这里用除
            } else {
                //最后两者刚好比例相同，其实可以不用写，刚好充满
                width = sWidth
                height = sHeight
            }
            //重设ImageView宽高
            imageView.layoutParams.width = width
            imageView.layoutParams.height = height
            //这样就获得了一个既适应屏幕又适应内部图片的ImageView，不用再纠结该给ImageView设定什么尺寸合适了
        }

        /**
         * 释放view资源,  防止内存泄漏
         */
        fun unbindDrawables(view: View?) {
            if (view == null) {
                return
            }
            if (view.background != null) {
                view.background.callback = null
            }
            if (view.drawingCache != null) {
                view.destroyDrawingCache()
            }
            if (view is ViewGroup) {
                for (i in 0 until (view as ViewGroup).getChildCount()) {
                    unbindDrawables((view as ViewGroup).getChildAt(i))
                }
                (view as ViewGroup).removeAllViews()
            }
        }

        /**
         * 设置textview中部分字体的样式
         *
         * @param tv
         * @param hlightAndClickText
         * @param color
         * @param isunderline
         * @param listener
         */
        fun setTextViewStyleAndOnClick(ctx: Context?, tv: TextView?, hlightAndClickText: String?, color: Int, textsize: Int, style: Int, isunderline: Boolean,
                                       listener: View.OnClickListener?) {
            val ss: SpannableString
            if (tv != null && hlightAndClickText != null) {
                val tvs = tv.text.toString()
                ss = SpannableString(tvs)
                val beginindex = tvs.indexOf(hlightAndClickText)
                if (beginindex == -1) {
                    return
                }
                val hlightAndClickTextlength = hlightAndClickText.length
                if (listener != null) {
                    ss.setSpan(MyClickableSpan(listener),  // Span接口用于实现对文本的修饰的具体内容
                            beginindex,  // 修饰的起始位置
                            beginindex + hlightAndClickTextlength,  // 修饰的结束位置
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
                if (color != -1) {
                    ss.setSpan(ForegroundColorSpan(color), beginindex, beginindex
                            + hlightAndClickTextlength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
                if (isunderline) {
                    ss.setSpan(UnderlineSpan(), beginindex, beginindex + hlightAndClickTextlength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                }

                // dip，如果为true，表示前面的字体大小单位为dip
                if (textsize != -1) {
                    ss.setSpan(AbsoluteSizeSpan(textsize, true), beginindex, beginindex + hlightAndClickTextlength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // 第二个参数boolean
                }

                // Typeface.NORMAL正常
                // Typeface.ITALIC斜体
                // Typeface.BOLD_ITALIC粗斜体
                if (style != -1){
                    ss.setSpan(StyleSpan(style), beginindex, beginindex + hlightAndClickTextlength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                } // Typeface.BOLD粗体

//            //匹配表情
//            String zhengze = "\\[[^\\]]+\\]";
//            // 通过传入的正则表达式来生成一个pattern
//            Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);
//            try {
//                ss = FaceConversionUtil.getInstace().dealExpression(ctx, ss, sinaPatten, 0, 2);
//            } catch (Exception e) {
//                Mylog.e("dealExpression", e.getMessage());
//            }
                tv.text = ss
                // 添加这一句，点击事件，拨号，http，发短信的超链接才能执行.
                if (listener != null) {
                    tv.movementMethod = CustomLinkMovementMethod.getInstance()
                }
            }
        }

        /**
         * 2016年2月26日
         * 描述:各个数组大小要一致
         * void
         * Administrator
         *
         * @param ctx
         * @param tv
         * @param hlightAndClickText
         * @param color
         * @param textsize
         * @param style
         * @param isunderline
         * @param listener
         */
        fun setTextViewStyleAndOnClick(ctx: Context, tv: TextView?, hlightAndClickText: Array<String>?, color: IntArray?, textsize: IntArray?, style: IntArray?,
                                       isunderline: BooleanArray?, listener: Array<View.OnClickListener?>?, alltextOnClickListener: View.OnClickListener?) {
            if (tv != null && hlightAndClickText != null) {
                val ss: SpannableString
                val tvs = tv.text.toString()
                var tvs_c = tv.text.toString()
                ss = SpannableString(tvs)
                var hascut = 0
                for (j in hlightAndClickText.indices) {
                    val beginindex = tvs_c.indexOf(hlightAndClickText[j])
                    if (beginindex == -1) {
                        continue
                    }
                    val hlightAndClickTextlength = hlightAndClickText[j].length
                    if (listener?.isNotEmpty() == true){
                        if (j < listener.size){
                            if (listener[j] != null) {
                                ss.setSpan(MyClickableSpan(listener[j]),  // Span接口用于实现对文本的修饰的具体内容
                                        beginindex + hascut,  // 修饰的起始位置
                                        beginindex + hlightAndClickTextlength + hascut,  // 修饰的结束位置
                                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                            }
                        }
                    }

                    if (color?.isNotEmpty() == true){
                        if (j < color.size){
                            if (color[j] != 0 && color[j] != -1) {
                                val fcs = ForegroundColorSpan(color[j])
                                ss.setSpan(fcs, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                            }
                        }
                    }
                    if (isunderline?.isNotEmpty() == true){
                        if (j < isunderline.size){
                            if (isunderline[j]) {
                                val uls = UnderlineSpan()
                                ss.setSpan(uls, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                            }
                        }
                    }
                    if (textsize?.isNotEmpty() == true){
                        if (j < textsize.size){
                            if (textsize[j] != 0 && textsize[j] != -1) {
                                ss.setSpan(AbsoluteSizeSpan(textsize[j], true), beginindex + hascut, beginindex + hlightAndClickTextlength + hascut,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // 第二个参数boolean
                            }
                        }
                    }
                    if (style?.isNotEmpty() == true){
                        if (j < style.size){
                            // dip，如果为true，表示前面的字体大小单位为dip
                            val ssp = StyleSpan(if (style[j] != 0 && style[j] != -1) style[j] else Typeface.NORMAL)
                            ss.setSpan(ssp, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // Typeface.BOLD粗体
                            // Typeface.NORMAL正常
                            // Typeface.ITALIC斜体
                            // Typeface.BOLD_ITALIC粗斜体
                        }
                    }

                    hascut += beginindex + hlightAndClickTextlength
                    if (hascut < tvs.length) {
                        tvs_c = tvs.substring(hascut)
                    }
                }
                if (alltextOnClickListener != null) {
                    val mcs2 = MyClickableSpan(alltextOnClickListener)
                    ss.setSpan(mcs2,  // Span接口用于实现对文本的修饰的具体内容
                            0,  // 修饰的起始位置
                            tvs.length,  // 修饰的结束位置
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
                ss.setSpan(BackgroundColorSpan(Color.TRANSPARENT), 0, tvs.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) //设置背景色透明
                tv.text = ss
                // 添加这一句，点击事件，拨号，http，发短信的超链接才能执行.
                if (listener != null) {
                    tv.movementMethod = CustomLinkMovementMethod.getInstance()
                }
            }
        }


        fun setTextViewStyleAndOnClick(ctx: Context?, tv: TextView?, hlightAndClickText: Array<String>?, color: Int, textsize: Int, style: Int,
                                       isunderline: Boolean, listener: View.OnClickListener?) {
            if (tv != null && hlightAndClickText != null) {
                val ss: SpannableString
                val tvs = tv.text.toString()
                var tvs_c = tv.text.toString()
                if (StringUtils.isEmpty(tvs_c)) {
                    return
                }
                ss = SpannableString(tvs)
                var hascut = 0
                for (url in hlightAndClickText) {
                    val beginindex = if (StringUtils.isEmpty(url)) -1 else tvs_c.indexOf(url)
                    if (beginindex == -1) {
                        break
                    }
                    val hlightAndClickTextlength = url.length
                    if (listener != null) {
                        ss.setSpan(MyClickableSpan(listener),  // Span接口用于实现对文本的修饰的具体内容
                                beginindex + hascut,  // 修饰的起始位置
                                beginindex + hlightAndClickTextlength + hascut,  // 修饰的结束位置
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    if (color != -1) {
                        val fcs = ForegroundColorSpan(color)
                        ss.setSpan(fcs, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    if (isunderline) {
                        val uls = UnderlineSpan()
                        ss.setSpan(uls, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    if (textsize != -1) {
                        ss.setSpan(AbsoluteSizeSpan(textsize, true), beginindex + hascut, beginindex + hlightAndClickTextlength + hascut,
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // 第二个参数boolean
                    }

                    // dip，如果为true，表示前面的字体大小单位为dip
                    val ssp = StyleSpan(if (style == -1) Typeface.NORMAL else style)
                    ss.setSpan(ssp, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // Typeface.BOLD粗体
                    // Typeface.NORMAL正常
                    // Typeface.ITALIC斜体
                    // Typeface.BOLD_ITALIC粗斜体
                    hascut += beginindex + hlightAndClickTextlength
                    if (hascut < tvs.length) {
                        tvs_c = tvs.substring(hascut)
                    }
                }
                tv.text = ss
                // 添加这一句，点击事件，拨号，http，发短信的超链接才能执行.
                if (listener != null) {
                    tv.movementMethod = CustomLinkMovementMethod.getInstance()
                }
            }
        }

        fun setTextViewStyleAndOnClick(ctx: Context?, tv: TextView?, hlightAndClickText: Array<String>?, color: Int, textsize: Int, style: Int,
                                       isunderline: Boolean, listener: Array<View.OnClickListener>?) {
            if (tv != null && hlightAndClickText != null) {
                val ss: SpannableString
                val tvs = tv.text.toString()
                var tvs_c = tv.text.toString()
                if (StringUtils.isEmpty(tvs_c)) {
                    return
                }
                ss = SpannableString(tvs)
                var hascut = 0
                for (url in hlightAndClickText) {
                    val beginindex = if (StringUtils.isEmpty(url)) -1 else tvs_c.indexOf(url)
                    if (beginindex == -1) {
                        break
                    }
                    val hlightAndClickTextlength = url.length
                    if (listener != null && listener.isNotEmpty()) {
                        var index = hlightAndClickText.indexOf(url)
                        if (index != -1){
                            ss.setSpan(MyClickableSpan(listener[index]),  // Span接口用于实现对文本的修饰的具体内容
                                    beginindex + hascut,  // 修饰的起始位置
                                    beginindex + hlightAndClickTextlength + hascut,  // 修饰的结束位置
                                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        }
                    }
                    if (color != -1) {
                        val fcs = ForegroundColorSpan(color)
                        ss.setSpan(fcs, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    if (isunderline) {
                        val uls = UnderlineSpan()
                        ss.setSpan(uls, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    if (textsize != -1) {
                        ss.setSpan(AbsoluteSizeSpan(textsize, true), beginindex + hascut, beginindex + hlightAndClickTextlength + hascut,
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // 第二个参数boolean
                    }

                    // dip，如果为true，表示前面的字体大小单位为dip
                    val ssp = StyleSpan(if (style == -1) Typeface.NORMAL else style)
                    ss.setSpan(ssp, beginindex + hascut, beginindex + hlightAndClickTextlength + hascut, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // Typeface.BOLD粗体
                    // Typeface.NORMAL正常
                    // Typeface.ITALIC斜体
                    // Typeface.BOLD_ITALIC粗斜体
                    hascut += beginindex + hlightAndClickTextlength
                    if (hascut < tvs.length) {
                        tvs_c = tvs.substring(hascut)
                    }
                }
                tv.text = ss
                // 添加这一句，点击事件，拨号，http，发短信的超链接才能执行.
                if (listener != null) {
                    tv.movementMethod = CustomLinkMovementMethod.getInstance()
                }
            }
        }

        /**
         * textview添加图片(有待验证)
         */
        fun setImageSpan(ctx: Context, tv: TextView?, spanText: String?, spanImgRes: Int){
            var span1 = SpannableStringBuilder()
            var sapn2 = SpannableString(spanText)
            val imageSpan = ImageSpan(ctx, spanImgRes)
            span1.append(sapn2).append(tv?.text)
            //setSpan插入内容的时候，起始位置不替换，会替换起始位置到终止位置间的内容，含终止位置。
            //Spanned.SPAN_EXCLUSIVE_EXCLUSIVE模式用来控制是否同步设置新插入的内容与start/end 位置的字体样式，此处没设置具体字体，所以可以随意设置
            var index = span1.indexOf(spanText!!)
            span1.setSpan(imageSpan, index, spanText.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
            tv?.setText(span1)
        }

        /**
         * 格式化超链接文本内容并设置点击处理
         */
        private fun getClickableHtml(html: String): CharSequence {
            val spannedHtml = Html.fromHtml(html)
            val clickableHtmlBuilder = SpannableStringBuilder(spannedHtml)
            val urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length, URLSpan::class.java)
            for (span in urls) {
                setLinkClickable(clickableHtmlBuilder, span)
            }
            return clickableHtmlBuilder
        }

        /*
         * 判断点击是否在view上
         */

        fun isTouchView(v: View?, ev: MotionEvent): Boolean {
            if (v == null) {
                return false
            }
            var `is` = false
            val l2 = intArrayOf(0, 0)
            v.getLocationInWindow(l2)
            LogUtil.i("ViewUtil", "点击view在屏幕上的坐标 x = " + l2[0] + "  y = " + l2[1])
            val left2 = l2[0]
            val top2 = l2[1]
            val bottom2 = top2 + v.height
            val right2 = left2 + v.width
            LogUtil.i("ViewUtil", "点击view ev.getX() = " + ev.x + "  ev.getY() = " + ev.y)
            LogUtil.i("ViewUtil", "点击view left2 = $left2  top2 = $top2  bottom2 = $bottom2  right2 = $right2")
            if (ev.x > left2 && ev.x < right2 && ev.y > top2 && ev.y < bottom2) {
                `is` = true
            }
            return `is`
        }

        /**
         * 设置点击超链接对应的处理内容
         */
        private fun setLinkClickable(clickableHtmlBuilder: SpannableStringBuilder, urlSpan: URLSpan) {
            val start = clickableHtmlBuilder.getSpanStart(urlSpan)
            val end = clickableHtmlBuilder.getSpanEnd(urlSpan)
            val flags = clickableHtmlBuilder.getSpanFlags(urlSpan)
            val clickableSpan: ClickableSpan = object : ClickableSpan() {
                override fun onClick(view: View) {}
            }
            clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags)
        }

        /**
         * 用于更改文字点击的事件和效果
         */
        private class MyClickableSpan(private val mOnClickListener: View.OnClickListener?) : ClickableSpan() {
            override fun onClick(widget: View) {
                mOnClickListener?.onClick(widget)
                if (widget != null && widget is TextView) {
                    widget.highlightColor = widget.getContext().resources.getColor(R.color.transparent) //方法重新设置文字背景为透明色
                }
            }

            override fun updateDrawState(ds: TextPaint) {
//            super.updateDrawState(ds);
//            //设置文本的颜色
//            ds.setColor(Color.RED);
//            //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线
//            ds.setUnderlineText(false);
            }
        }
        @JvmStatic
        fun appendSpan(tv: TextView, span: Spannable){
            val spanText = SpannableStringBuilder(tv.text)
            spanText.append(span)
            tv.text = spanText
            tv.movementMethod = CustomLinkMovementMethod.getInstance()
        }
        @JvmStatic
        fun appendText(tv: TextView, span: CharSequence){
            val spanText = SpannableStringBuilder(tv.text)
            spanText.append(span)
            tv.text = spanText
            tv.movementMethod = CustomLinkMovementMethod.getInstance()
        }

        fun appendText(tv: TextView, span: SpannableString){
            val spanText = SpannableStringBuilder(tv.text)
            spanText.append(span)
            tv.text = spanText
            tv.movementMethod = CustomLinkMovementMethod.getInstance()
        }

        fun createImgSpan(ctx: Context, spanText: String?, resImg: Int): Spannable{
            val ss = SpannableString(spanText)
            ss.setSpan(SelfImageSpan(ctx, resImg, spanText), 0, spanText!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            return ss
        }

        fun createReplacementSpan(ctx: Context, spanText: String?, textColor: Int, bgColor: Int, radius: Int, maxLine: Int, maxWidth: Int): Spannable{
            val ss = SpannableString(spanText)
            ss.setSpan(RadiusBackgroundSpan(textColor, bgColor, radius, maxLine, maxWidth), 0, spanText!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
//            if (textColor != -1) {
//                ss.setSpan(ForegroundColorSpan(textColor), 0, spanText!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
//            }
            return ss
        }
        @JvmStatic
        fun createSpan(spanText: String?, color: Int, textsize: Int, style: Int, isunderline: Boolean, listener: View.OnClickListener?): Spannable{
            val ss = SpannableString(spanText)
            if (listener != null) {
                ss.setSpan(MyClickableSpan(listener),  // Span接口用于实现对文本的修饰的具体内容
                        0,  // 修饰的起始位置
                        spanText!!.length,  // 修饰的结束位置
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            if (color != -1) {
                ss.setSpan(ForegroundColorSpan(color), 0, spanText!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            if (isunderline) {
                ss.setSpan(UnderlineSpan(), 0, spanText!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

            // dip，如果为true，表示前面的字体大小单位为dip
            if (textsize != -1) {
//                ss.setSpan(AbsoluteSizeSpan(textsize, true), 0, spanText!!.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // 第二个参数boolean
                ss.setSpan(AbsoluteSizeSpan(DisplayUtil.sptopx(BaseManager.getInstance().getContext(), textsize.toFloat())), 0, spanText!!.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)//换成sp单位
            }

            // Typeface.NORMAL正常
            // Typeface.ITALIC斜体
            // Typeface.BOLD_ITALIC粗斜体
            if (style != -1){
                ss.setSpan(StyleSpan(style), 0, spanText!!.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            } // Typeface.BOLD粗体

            return ss
        }

        fun autoSplitText(tv: TextView, indent: String): String? {
            val rawText = tv.text.toString() //原始文本
            val tvPaint: Paint = tv.paint //paint，包含字体等信息
            val tvWidth = (tv.width - tv.paddingLeft - tv.paddingRight).toFloat() //控件可用宽度

            //将缩进处理成空格
            var indentSpace = ""
            var indentWidth = 0f
            if (!TextUtils.isEmpty(indent)) {
                val rawIndentWidth = tvPaint.measureText(indent)
                if (rawIndentWidth < tvWidth) {
                    while (tvPaint.measureText(indentSpace).also { indentWidth = it } < rawIndentWidth) {
                        indentSpace += " "
                    }
                }
            }

            //将原始文本按行拆分
            val rawTextLines = rawText.replace("\r".toRegex(), "").split("\n".toRegex()).toTypedArray()
            val sbNewText = StringBuilder()
            for (rawTextLine in rawTextLines) {
                if (!StringUtils.isEmpty(rawTextLine)){
                    if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                        //如果整行宽度在控件可用宽度之内，就不处理了
                        sbNewText.append(rawTextLine)
                    } else {
                        //如果整行宽度超过控件可用宽度，则按字符测量，在超过可用宽度的前一个字符处手动换行
                        var lineWidth = 0f
                        var cnt = 0
                        while (cnt != rawTextLine.length) {
                            val ch = rawTextLine[cnt]
                            //从手动换行的第二行开始，加上悬挂缩进
                            if (lineWidth < 0.1f && cnt != 0) {
                                sbNewText.append(indentSpace)
                                lineWidth += indentWidth
                            }
                            lineWidth += tvPaint.measureText(ch.toString())
                            if (lineWidth <= tvWidth) {
                                sbNewText.append(ch)
                            } else {
                                sbNewText.append("\n")
                                lineWidth = 0f
                                --cnt
                            }
                            ++cnt
                        }
                    }
                }

                sbNewText.append("\n")
            }

            //把结尾多余的\n去掉
            if (!rawText.endsWith("\n")) {
                sbNewText.deleteCharAt(sbNewText.length - 1)
            }
            return sbNewText.toString()
        }

    }
}